#include<iostream>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

class name_fifo
{
public:
    name_fifo(const std::string path,const std::string name)
        :_path(path)
        ,_name(name)
    {
        umask(0);
        _fifoname+=path+"/"+name;
        int n=mkfifo(_fifoname.c_str(),0666);
        if(n==-1)
        {
            std::cout<<"mkfifo failed!"<<std::endl;
        }
        else
        {
            std::cout<<"mkfifo success!"<<std::endl;
        }
    }
    ~name_fifo()
    {
        unlink(_fifoname.c_str());
    }
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};


class oper_fifo
{
public:
    oper_fifo(const std::string path,const std::string name)
        :_path(path)
        ,_name(name)
    {
        _fifoname+=_path+"/"+_name;
    }
    ~oper_fifo()
    {}
    void open_for_read()
    {
        int ret=open(_fifoname.c_str(),O_RDONLY);
        if(ret>0)
        {
            _fd=ret;
            std::cout<<"open fifo success!"<<std::endl;
        }
        else
        {
            std::cout<<"open fifo failed!"<<std::endl;
        }
    }
    void open_for_write()
    {
        int ret=open(_fifoname.c_str(),O_WRONLY);
        if(ret>0)
        {
            _fd=ret;
             std::cout<<"open fifo success!"<<std::endl;
        }
        else
        {
             std::cout<<"open fifo failed!"<<std::endl;
        }

    }
    void Read()
    {
        while(1)
        {
            char rd_buffer[1024];
            int ret=read(_fd,rd_buffer,sizeof(rd_buffer)-1);
            if(ret>0)
            {
                rd_buffer[ret]='0';
                std::cout<<"client say:"<<rd_buffer<<std::endl;
            }
            else if(ret==0)
            {
                //client退出读端读到文件末尾
                std::cout<<"client exit me too"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"read failed!"<<std::endl;
                break;
            }
        }
    }
    void Write()
    {
        while(1)
        {
            std::string messager;
            int cnt=1;
            pid_t id=getpid();
            std::cout<<"Please Enter:"<<std::endl;
            std::getline(std::cin,messager);
            messager+=(",messager number"+std::to_string(cnt)+"["+std::to_string(id)+"]");
            int ret=write(_fd,messager.c_str(),messager.size());
            (void)ret;
            cnt++;
        }
    }
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};
